package bluetooth;

import java.io.IOException;
import java.util.Vector;

import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;


import javax.microedition.lcdui.List;

public class BlueDeviceSearcher implements Runnable, DiscoveryListener {

    //存储发现的设备和服务的集合
    private Vector devices = new Vector();
    //蓝牙发现代理类
    private DiscoveryAgent discoveryAgent = null;
    //主界面
    private List list = null;
    //设备列表
    private int index=0;

    public BlueDeviceSearcher(List display_list) {
        //list to show the progress and result
        list = display_list;
    }

    public synchronized void run() {
        //Gauge g = new Gauge("Searching service..", false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING);
        //list.append(g);
        //如果初始化失败
        list.setTitle("Searching..");
        if (!initLocalDevice()) {
            
            //list.insert(0, "bluetooth init failed~", null);
            //clientForm.appendInfo();
            return;
        }
        try {
            discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return;
        }
        try {
            //阻塞，由inquiryCompleted函数回调唤醒
            wait();
        } catch (InterruptedException ex) {
            System.out.println(ex.getMessage());
            //clientForm.appendInfo(ex.getMessage());
            return;
        }
        //添加显示信息
        System.out.println("search device completed,find " + devices.size() + " devices~");
        list.setTitle("Complete! " + Integer.toString(devices.size()));
        
    }

    /**
     * 初始化本地蓝牙设备
     * @return
     */
    private boolean initLocalDevice() {
        boolean isReady = false;
        try {
            LocalDevice localDevice = LocalDevice.getLocalDevice();
            discoveryAgent = localDevice.getDiscoveryAgent();
            //设置自身设备不可访问性
            localDevice.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
            isReady = true;
        } catch (Exception ex) {
            isReady = false;
        }
        return isReady;
    }

    public void cancelSearchDevice() {
        discoveryAgent.cancelInquiry(this);
    }

    public Vector getDevices() {
        return devices;

    }

    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
       


        if (devices.indexOf(btDevice) == -1) {
           
                devices.addElement(btDevice);

                //StringItem s = new StringItem(Integer.toString(devices.indexOf(btDevice)), btDevice.getFriendlyName(true));
                list.insert(index,"Server #"+Integer.toString(devices.indexOf(btDevice)), null);
                index++;
                
                /*
                try{
                    list.insert(0,"Server:"+btDevice.getFriendlyName(true), null);
                }catch (IOException ex){
                    list.setTitle("Get name failed"+ex);
                }
                 * 
                 */
                //list.insert(devices.indexOf(btDevice), btDevice.getFriendlyName(true), null);
            //indexForm.append(s);
        }
        //indexForm.append(s);


    }

    public void inquiryCompleted(int disType) {
        synchronized (this) {
            int x=0;
            for(x=0;x<devices.size();x++){
                BlueComm bc = new BlueComm((RemoteDevice) devices.elementAt(x));
                list.set(x, "Server("+x+"):"+bc.getDeviceName(), null);
            }
            notify();
        }
    }

    public void serviceSearchCompleted(int i, int i1) {
        
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    
    public void servicesDiscovered(int i, ServiceRecord[] srs) {
 
        throw new UnsupportedOperationException("Not supported yet.");
        
    }
}
